package com.ruoyi.web.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import com.ruoyi.system.mapper.H5RegisterMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.domain.WorkEnterprise;
import com.ruoyi.web.domain.WorkEnterpriseUser;
import com.ruoyi.web.domain.dto.EnterpriseBindDto;
import com.ruoyi.web.mapper.SysAreaMapper;
import com.ruoyi.web.service.ThirdPartyUserService;
import com.ruoyi.web.service.WorkEnterpriseService;
import com.ruoyi.web.service.WorkEnterpriseUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ThirdPartyUserServiceImpl implements ThirdPartyUserService {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private WorkEnterpriseUserService workEnterpriseUserService;

    @Autowired
    private H5RegisterMapper h5RegisterMapper;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private SysAreaMapper sysAreaMapper;

    @Autowired
    private WorkEnterpriseService workEnterpriseService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult bindEnterprise(EnterpriseBindDto dto) {
        // 查询所绑定的企业主体user是否已存在
        String enterpriseUnicode = dto.getEnterpriseUnicode().toUpperCase();
        String uuid = dto.getUuid();
        String enterpriseName = dto.getEnterpriseName();
        SysUser userDto = new SysUser();
        userDto.setUserName(enterpriseUnicode);
        userDto.setExactMatch("1");
        // 根据提交的企业名称查询企业库中数据的社会统一信用代码，并判断用户提交的社会统一信用代码是否有误
        WorkEnterprise enterprise = workEnterpriseService.getOne(new LambdaQueryWrapper<WorkEnterprise>().eq(WorkEnterprise::getCompanyName, enterpriseName));
        if (enterprise == null) {
            return AjaxResult.error("企业主体不存在");
        }
        if (! StrUtil.equals(enterpriseUnicode, enterprise.getUnicode().toUpperCase())) {
            return AjaxResult.error("社会统一信用代码与企业名称不匹配");
        }
        List<SysUser> list = sysUserService.selectUserList(userDto);
        if (list.size() == 0) {
            // 不存在，则首先创建一个企业主体user
            SysUser sysUser = new SysUser();
            sysUser.setUserName(enterpriseUnicode);
            sysUser.setNickName(enterpriseName);
            String password = enterpriseUnicode;
            if (enterpriseUnicode.length() >= 6) {
                password = enterpriseUnicode.substring(enterpriseUnicode.length() - 6);
            }
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            sysUser.setRemark("企业人员");
            sysUser.setCreateBy("uuid_" + uuid);
            sysUser.setLoginSource(dto.getLoginSource());
            if (StrUtil.equals(dto.getSource(), "1")) {
                // 统一身份认证端，省市区参数值为地区编码，可直接赋值
                sysUser.setProvince(dto.getProvince());
                sysUser.setCity(dto.getCity());
                sysUser.setDistrict(dto.getDistrict());
            } else {
                // 爱山东端，省市区参数值为地区名称，需先查询省市区编码
                String provinceCode = sysAreaMapper.queryCodeByName(dto.getProvince());
                sysUser.setProvince(provinceCode);
                String cityCode = sysAreaMapper.selectCodeByNameAndParentCode(dto.getCity(), provinceCode);
                sysUser.setCity(cityCode);
                sysUser.setDistrict(sysAreaMapper.selectCodeByNameAndParentCode(dto.getDistrict(), cityCode));
            }
            boolean regFlag = sysUserService.insertUser(sysUser) > 0;
            String msg = "";
            if (! regFlag) {
                msg = "注册失败,请联系系统管理人员";
            } else {
                // 查询新的用户id，设置一个普通角色
                Long userId = h5RegisterMapper.queryRegisterUserId(sysUser.getUserName());
                if(userId == null) {
                    msg = "注册失败,请联系系统管理人员";
                } else {
                    // 普通角色
                    h5RegisterMapper.insertRegisterUserRole(userId, 2L);
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(enterpriseName, Constants.REGISTER, MessageUtils.message("user.register.success")));
                }
            }
            if (StringUtils.isNotEmpty(msg)) {
                return AjaxResult.error(msg);
            }
        }

        // 将第三方用户的uuid与对应企业的USCC进行绑定
        WorkEnterpriseUser workEnterpriseUser = new WorkEnterpriseUser();
        workEnterpriseUser.setId(IdUtils.simpleUUID());
        workEnterpriseUser.setUnicode(enterpriseUnicode);
        workEnterpriseUser.setNatureUserUuid(uuid);
        workEnterpriseUser.setCreateTime(new Date());
        workEnterpriseUserService.save(workEnterpriseUser);

        String token = sysLoginService.login(enterpriseUnicode, "", "", "", UserDetailsServiceImpl.AI_SHAN_DONG_SSO_FLAG);
        AjaxResult ajax = AjaxResult.success();
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
}
